/*
 * @Author: 杨有财
 * @Date: 2025-02-27 08:37:09
 * @LastEditTime: 2025-03-01 22:26:52
 * @LastEditors: 杨有财
 * @Description: 路由守卫,在 index.ts 中注册
 */

import 'nprogress/nprogress.css'; // progress bar style

import NProgress from 'nprogress'; // progress bar
import { Router, RouteRecordRaw } from 'vue-router';

import { getPermissionStore, useUserStore } from '@/store';

import whiteListRouters from './whiteListRouters';

NProgress.configure({ showSpinner: false });

export function registerNavigationGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();

    const permissionStore = getPermissionStore();

    const userStore = useUserStore();

    const pathName = getFirstRoute(permissionStore.routers as RouteRecordRaw[]);

    if (userStore.token) {
      // 如果已经登录再次访问登录页面，方法第一个默认路由
      if (to.path === '/login') {
        next({ path: pathName });
        NProgress.done();
      }
      await userStore.getUserInfo();

      const { routers } = permissionStore;

      if (routers && routers.length > 0) {
        next();
      } else {
        try {
          await permissionStore.initRoutes();
          next({ ...to });
        } catch (error) {
          MessagePlugin.error(error.message);
          await userStore.logout();
          next({
            path: '/login',
            query: { redirect: encodeURIComponent(to.fullPath) },
          });
          NProgress.done();
        }
      }
    } else {
      /* white list router */
      if (whiteListRouters.indexOf(to.path) !== -1) {
        next();
      } else {
        next({
          path: '/login',
          query: { redirect: encodeURIComponent(to.fullPath) },
        });
      }
      NProgress.done();
    }
  });

  router.afterEach((to) => {
    if (to.path === '/login') {
      const userStore = useUserStore();
      const permissionStore = getPermissionStore();

      userStore.logout();
      permissionStore.restoreRoutes();
    }
    NProgress.done();
  });
}

/**
 * 获取第一个路由地址
 */
function getFirstRoute(router: RouteRecordRaw[]) {
  if (router.length > 0) {
    let path = `${router[0].path}`;
    if (router[0].children && router[0].children.length > 0) {
      path += `/${getFirstRoute(router[0].children)}`;
    }
    return path;
  }
  return '';
}
